package com.example.app3;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GameModel {
    private List<Card> cards;
    private int pairs;
    private int attempts;
    private Card firstFlippedCard;
    private Card secondFlippedCard;
    private boolean isProcessing;

    public Card getSecondFlippedCard() {
        return secondFlippedCard;
    }
    public GameModel(int pairs, List<Integer> imageResIds) {
        this.pairs = pairs;
        this.attempts = 0;
        this.cards = new ArrayList<>();
        this.isProcessing = false;
        initCards(imageResIds);
    }

    private void initCards(List<Integer> imageResIds) {
        for (int i = 0; i < pairs; i++) {
            int imageResId = imageResIds.get(i % imageResIds.size());
            cards.add(new Card(i * 2, imageResId));
            cards.add(new Card(i * 2 + 1, imageResId));
        }
        Collections.shuffle(cards);
    }

    public List<Card> getCards() { return cards; }
    public int getAttempts() { return attempts; }

    public boolean flipCard(int position) {
        if (isProcessing) return false;
        Card card = cards.get(position);
        if (card.isMatched() || card.isFlipped()) return false;

        if (firstFlippedCard == null) {
            firstFlippedCard = card;
            firstFlippedCard.setFlipped(true);
            return true;
        } else if (secondFlippedCard == null && card != firstFlippedCard) {
            secondFlippedCard = card;
            secondFlippedCard.setFlipped(true);
            attempts++;
            isProcessing = true;
            return true;
        }
        return false;
    }

    public boolean checkForMatch() {
        if (firstFlippedCard == null || secondFlippedCard == null) return false;
        boolean isMatch = firstFlippedCard.getImageResId() == secondFlippedCard.getImageResId();
        if (isMatch) {
            firstFlippedCard.setMatched(true);
            secondFlippedCard.setMatched(true);
        }
        return isMatch;
    }

    public void resetFlippedCards() {
        if (firstFlippedCard != null && !firstFlippedCard.isMatched()) {
            firstFlippedCard.setFlipped(false);
        }
        if (secondFlippedCard != null && !secondFlippedCard.isMatched()) {
            secondFlippedCard.setFlipped(false);
        }
        firstFlippedCard = null;
        secondFlippedCard = null;
        isProcessing = false;
    }

    public boolean isGameOver() {
        for (Card card : cards) {
            if (!card.isMatched()) return false;
        }
        return true;
    }

    public void restartGame() {
        attempts = 0;
        firstFlippedCard = null;
        secondFlippedCard = null;
        isProcessing = false;
        for (Card card : cards) {
            card.setFlipped(false);
            card.setMatched(false);
        }
        Collections.shuffle(cards);
    }
}